/**
 * 
 */
package org.storagemanagement.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.storagemanagement.DO.StockDO;
import org.storagemanagement.constant.StorageConstant;
import org.storagemanagement.model.ImportRecordQuery;
import org.storagemanagement.model.ImportRecordVO;
import org.storagemanagement.model.LoginVO;
import org.storagemanagement.services.ImportService;
import org.storagemanagement.services.StockService;
import org.storagemanagement.uti.LoginUtils;

/**
 * @author Jason.zhang
 * 
 */
@Controller
@RequestMapping("/import")
@SessionAttributes({ StorageConstant.LOGIN_VO })
public class ImportController {
	@Resource
	private ImportService importService;
	@Resource
	private StockService stockService;

	/**
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/get_records")
	public @ResponseBody
	List<ImportRecordVO> getRecords(@ModelAttribute ImportRecordQuery importQuery, @ModelAttribute(StorageConstant.LOGIN_VO) LoginVO loginVO) {
		if(!LoginUtils.isAuthed(loginVO)){
			throw new RuntimeException("Please login first");
		}
		
		List<ImportRecordVO> importRecords = importService.getImportRecords(importQuery);
		return importRecords;
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/add_record")
	public @ResponseBody
	boolean addRecord(@RequestBody ImportRecordVO record, @ModelAttribute(StorageConstant.LOGIN_VO) LoginVO loginVO) {
		if(!LoginUtils.isAuthed(loginVO)){
			throw new RuntimeException("Please login first");
		}
		
		boolean flag = false;
		try {
			importService.addImportRecord(record,"Jason");
			
			StockDO stockDO = new StockDO();
			stockDO.setBatchNo(record.getBatchNo());
			stockDO.setCustomerId(record.getCustomerId());
			stockDO.setProduct(record.getProduct());
			stockDO.setQuantity(record.getQuantity());
			stockService.addStock(stockDO);
			flag = true;
		} catch (Exception ex) {
			flag = false;
		}
		return flag;
	}

	public void setImportService(ImportService importService) {
		this.importService = importService;
	}

	public void setStockService(StockService stockService) {
		this.stockService = stockService;
	}

}
